<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分配角色</title>
    <script src="/layui/layui.js"></script>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <script src="/js/jquery.js"></script>
    <script src="/js/myAjax.js"></script>
</head>
<body>
<div type="hidden" id="userId"></div>
<div id="compareRole" style="margin-left: 50px;margin-top: 50px"></div>
</body>
<script>
    layui.use('transfer', function () {
        var transfer = layui.transfer;

        function findRole() {
            let data = myAjax('/r/role/searchAll', 'post', {});
            let data1 = [];
            for (let i = 0; i < data.data.length; i++) {
                data1.push({"value": data.data[i].id, "title": data.data[i].roleName});
            }
            return data1;
        }

        function findByUserId() {
            let id = sessionStorage.getItem("userId");
            let data2 = [];
            let result = myAjax('/u/user/findByUserId', 'post', {id: id});
            console.log(result);
            for (let i = 0; i < result.data.length; i++) {
                data2.push(result.data[i].roleId);
            }
            return data2;
        }

        /**
         * 先查询出所有的角色信息展示在左侧栏，然后去查询用户所拥有的角色id 赋值给value，然后右侧展示拥有角色的数据
         * @type {[]}
         */
        let data = findRole();
        let value = findByUserId();
        //渲染
        transfer.render({
            elem: '#compareRole'  //绑定元素
            , showSearch: true
            , title: ['未拥有', '已拥有']
            , data: data
            , value: value
            , onchange: function (data, index) {
                //index=0就是添加的数据
                //index=1就是删除的数据
                let  id =parseInt(sessionStorage.getItem("userId")) ;
                // console.log(id,data[0].value);
                if (data.length>1){
                    layer.msg("抱歉！每个用户只能添加一个角色")
                }else {
                    if (index === 0) {
                        let result = myAjax('/u/user/addRole', 'post', {userId:id,roleId:data[0].value});
                        if (result.code === 200) {
                            layer.msg("添加成功");
                        } else {
                            layer.msg("添加失败")
                        }
                    }
                    if (index === 1) {
                        console.log("我进来了")
                        let result = myAjax('/u/user/deleteRole', 'post',{roleId:data[0].value,userId:id});
                        if (result.code === 200) {
                            layer.msg("剔除成功");
                        } else {
                            layer.msg("剔除失败")
                        }
                    }
                }
            }
        });
    });
</script>
</html>